/**
 * 
 */
package com.service;

import java.util.List;

import org.apache.log4j.Logger;

import com.model.CpAccount;
import com.utils.dbcp.ConnectionManager;
import com.utils.dbcp.ModelGenerator;
import com.utils.encrypt.MD5;

public class CpAccountServiceImpl extends AbstractDateService implements CpAccountService
{
	private Logger logger;
	
	private final String ENCRYPT_KEY = "@$^adpopo^$@";
	
	public CpAccountServiceImpl()
	{
		logger = Logger.getLogger(this.getClass());
	}
	
	
	public String encrypt(String str)
	{
		return MD5.computeMD5(str + ENCRYPT_KEY);
	}
	
	@Override
	public CpAccount getCpAccount(String id, String password) 
	{		
		CpAccount a = getCpAccount(id);
		if (a != null && (a.getPassword().equals(password) || a.getPassword().equals(encrypt(password))))
			return a;
		return null;
	}

	@Override
	public CpAccount getCpAccount(String id) 
	{
		String sql = "select * from t_cpaccount where id='" + id + "'";
		ModelGenerator<CpAccount> dbcpmg = new ModelGenerator<CpAccount>(CpAccount.class);
		return dbcpmg.generate(base, sql);
	}

	@Override
	public List<CpAccount> getCpAccounts()
	{
		String sql = "select * from t_cpaccount";
		logger.debug("sql: " + sql);
		ModelGenerator<CpAccount> dbcpmg = new ModelGenerator<CpAccount>(CpAccount.class);
		return dbcpmg.generateList(base, sql);
	}
	
	@Override
	public boolean saveCpAccount(String type, CpAccount account)
	{
		
		String sql = "";
		if (type.equalsIgnoreCase("insert"))
		{
				sql = 
				"insert into t_cpaccount(id,name,password,cpid,channelid,type,remark,createuser,createdate,menuvalue) " +
				"values('" + encodeDb(account.getId()) + "','" + encodeDb(account.getName()) + "','" + encrypt(account.getPassword()) + "','" +
						account.getCpId()+ "','" +
						account.getChannelid()+ "','" +
						account.getType()+ "','" + account.getRemark() + "','"
						+ account.getCreateuser() + "','" + account.getCreatedate() + "','" + account.getMenuvalue()+ "')";
			
		}
		else if (type.equalsIgnoreCase("update"))
		{
			sql = 
				"update t_cpaccount set name='" + encodeDb(account.getName()) + "'," +
						"remark='" + account.getRemark() + 
						"',cpid='"+account.getCpId()+
						"',channelid='"+account.getChannelid()+"',menuvalue='"+account.getMenuvalue()+"'  " + 
				" where id='" + account.getId() + "'";
		}
		else if (type.equalsIgnoreCase("delete"))
		{
			sql = "delete from t_cpaccount where id='" + encodeDb(account.getId()) + "'";
		}
		else
		{
			sql = "";
		}
		logger.debug("sql: " + sql);
		return ConnectionManager.getInstance().execute(base, sql);
	}
	public boolean updatePassword( String id, String password)
	{
		String sql =
				"update t_cpaccount set password='" + encrypt(password) + "' " +
				"where id='" + id + "'";
		logger.debug("sql: " + sql);
		return ConnectionManager.getInstance().execute(base, sql);
	}

}
